//
//  ATStaTool.m
//  YanZhao
//
//  Created by 林涛 on 15/4/30.
//  Copyright (c) 2015年 AT. All rights reserved.
//

#import "ATStaTool.h"
#import "ATLocTool.h"
#import "ATAlertView.h"
#import <UMMobClick/MobClick.h>
#import <AudioToolbox/AudioToolbox.h>
#import <UMengMessage/UMessage.h>
#import "BaseWebController.h"

#ifdef DEBUG
#define ATLog(...) NSLog(__VA_ARGS__)
#else
#define ATLog(...) /* */
#endif
NSString * const ATReciveRemotePushNotification = @"ATReciveRemotePushNotification";
@interface ATStaTool ()
{
    
}
#if defined(AliFeedback_ENABLE)
@property (nonatomic, strong) YWFeedbackKit *feedbackKit;
#endif
@end

@implementation ATStaTool
static ATStaTool *_instance;
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
} 
+ (instancetype)allocWithZone:(NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

+ (void)initToolWithLaunchOptions:(NSDictionary *)launchOptions {
    BOOL isInDebugMode = NO;
#if DEBUG
    isInDebugMode = YES;
#endif
    UMAnalyticsConfig *config = [UMAnalyticsConfig sharedInstance];
    config.appKey = UMAppKey;
    config.secret = UMAppSec;
    config.channelId = (isInDebugMode ? @"Developers" : @"App Store");
    config.bCrashReportEnabled = YES;
    config.ePolicy = BATCH;
    config.eSType = E_UM_NORMAL;
    [MobClick startWithConfigure:config];
    [UMessage startWithAppkey:UMAppKey launchOptions:launchOptions];
    [UMessage setLogEnabled:isInDebugMode];
    [UMessage setAutoAlert:NO];
    [UMessage setBadgeClear:YES];
    UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert |
                                                                                             UIUserNotificationTypeSound)
                                                                                 categories:nil];
    [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
    if (launchOptions) {
        NSDictionary *dic = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (dic == nil) {
            UILocalNotification *localNoti = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
            dic = localNoti.userInfo;
        }
        if ( dic != nil) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self didReceiveNotification:dic dealWithAsk:NO];
            });
        }
    }
    
//            Class cls = NSClassFromString(@"UMANUtil");
//            SEL deviceIDSelector = @selector(openUDIDString);
//            NSString *deviceID = nil;
//            if(cls && [cls respondsToSelector:deviceIDSelector]){
//                deviceID = [cls performSelector:deviceIDSelector];
//            }
//            NSData* jsonData = [NSJSONSerialization dataWithJSONObject:@{@"oid" : deviceID}
//                                                               options:NSJSONWritingPrettyPrinted
//                                                                 error:nil];
//    
//            ATLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
    
    [ATLocTool LocationWithCompeletion:^(CLLocation *currentLocation, ATLocStatus status) {
        if (status == ATLocStatusSuccess) {
            [MobClick setLocation:currentLocation];
            [UMessage setLocation:currentLocation];
        }
    }];
}

#if defined(UMFeedback_ENABLE)
+ (UIViewController *)feedBackViewController {
    return [UMFeedback feedbackViewController];
}
+ (UIViewController *)feedBackModalViewController {
    return [UMFeedback feedbackModalViewController];
}
#endif
#pragma mark - 第三方推送SDK

+ (void)registerDeviceToken:(NSData *)deviceToken {
    [UMessage registerDeviceToken:deviceToken];
#if defined(UMFeedback_ENABLE)
    [UMessage addAlias:[UMFeedback uuid] type:[UMFeedback messageType] response:^(id responseObject, NSError *error) {
        ATLog(@"error %@, responseObject %@", error, responseObject);
    }];
#endif
    NSString *token = [NSString stringWithFormat:@"%@", deviceToken];
    token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    ATLog(@"DeviceToken: %@", token);
    [[self sharedInstance] setDeviceToken:token];
    [self updateDeviceTokenTags];
}
+ (void)updateDeviceTokenTags {
//    [LJHttpTool POST:LJ_REGISTER_DEVICE
//              params:@{@"deviceId" : SafeDicObj([ATDevTool IDFAString]),
//                       @"deviceType" : SafeDicObj(@"ios"),
//                       @"pushToken" : SafeDicObj([[self sharedInstance] deviceToken]),
//                       @"channelId" : SafeDicObj(APP_CHANNEL),
//                       }
//             success:^(id responseObject) {
//                 ATLog(@"success update deviceToken");
//             }
//             failure:^(NSString *errorMsg) {
//                 ATLog(@"error update deviceToken : %@", errorMsg);
//             }];
}

+ (void)didReceiveNotification:(NSDictionary *)userInfo dealWithAsk:(BOOL)ask {
    ATLog(@"didReceiveNotification %@", userInfo);
    [UMessage didReceiveRemoteNotification:userInfo];
#if defined(UMFeedback_ENABLE)
    [UMFeedback didReceiveRemoteNotification:userInfo];
#endif
    if (ask) {
        [self activeReciveUserInfo:userInfo];
    }
    else {
        [self dealWithUserInfo:userInfo];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:ATReciveRemotePushNotification object:nil];
}

#pragma mark - 推送处理

+ (void)localNotificationWithUserInfo:(NSDictionary *)userInfo
{
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    
    notification.fireDate       = [[NSDate new] dateByAddingTimeInterval:2];
    notification.repeatInterval = 0;
    notification.timeZone       = [NSTimeZone defaultTimeZone];
    notification.alertBody      = userInfo[@"aps"][@"alert"];
    notification.soundName      = UILocalNotificationDefaultSoundName;
    notification.userInfo       = userInfo;
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    [[NSNotificationCenter defaultCenter] postNotificationName:ATReciveRemotePushNotification object:nil];
}

+ (void)activeReciveUserInfo:(NSDictionary *)userInfo
{
    int showAlert = [userInfo[@"action_showAlert"] intValue];
    UINavigationController *nav = (UINavigationController *)[UIViewController rootTopPresentedController];
    nav = [nav isKindOfClass:[UINavigationController class]] ? nav :  nav.navigationController;
    if (showAlert) {
        [ATAlertView showTitle:ATLocalizedString(@"Tips", @"温馨提示")
                       message:userInfo[@"aps"][@"alert"]
                 normalButtons:@[ATLocalizedString(@"Cancel", @"取消")]
              highlightButtons:@[ATLocalizedString(@"Go", @"去看看")]
                    completion:^(NSInteger index, NSString *buttonTitle) {
                        if (index == 1) {
                            [self dealWithUserInfo:userInfo];
                        }
                        else {
                            [self localNotificationWithUserInfo:userInfo];
                        }
                    }];
    }
    else {
        ATLog(@"AudioServicesPlaySystemSound 1007, localNotificationWithUserInfo");
        AudioServicesPlaySystemSound(1007);
        [self localNotificationWithUserInfo:userInfo];
    }
}

+ (void)presentViewController:(UIViewController *)vc {
    if (vc == nil) {
        return;
    }
    UIViewController *visibleVC = [UIViewController rootTopPresentedController];
    if (visibleVC == nil) {
        return;
    }
    [visibleVC presentViewController:[[BaseNavigationController alloc] initWithRootViewController:vc]
                            animated:YES
                          completion:nil];
}

+ (void)dealWithUserInfo:(NSDictionary *)userInfo
{
    ATLog(@"Receive remote notification : %@",userInfo);
    [[NSNotificationCenter defaultCenter] postNotificationName:ATReciveRemotePushNotification object:nil];
    [UMessage sendClickReportForRemoteNotification:userInfo];
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    if (userInfo[@"action_msgType"] == nil) {
        return;
    }
    int type = [userInfo[@"action_msgType"] intValue];
    NSDictionary *dic = userInfo;
    switch (type) {
        case 0:{
            NSString *url = dic[@"url"];
            if (url.length) {
                [self presentViewController:[BaseWebController vcWithURLString:url]];
            }
            break;
        }
        default:
            break;
    }
}

#pragma mark -- 统计处理
+ (void)logPageView:(NSString *)pageName seconds:(int)seconds {
    [MobClick logPageView:pageName seconds:seconds];
}
+ (void)beginLogPageView:(NSString *)pageName {
    [MobClick beginLogPageView:pageName];
}
+ (void)endLogPageView:(NSString *)pageName {
    [MobClick endLogPageView:pageName];
}
+ (void)logClick:(NSString *)name {
    [MobClick event:@"click" attributes:@{@"type":SafeDicObj(name)}];
}
+ (void)logDevice:(NSString *)name {
    [MobClick event:@"device" attributes:@{@"type":SafeDicObj(name)}];
}
#pragma mark - getter
#if defined(AliFeedback_ENABLE)
+ (YWFeedbackKit *)feedbackKit {
    return [[self sharedInstance] feedbackKit];
}
- (YWFeedbackKit *)feedbackKit {
    if (!_feedbackKit) {
        _feedbackKit = [[YWFeedbackKit alloc] initWithAppKey:ALiBaiChuanAppKey];
    }
    return _feedbackKit;
}
#endif
@end
